package ltd.dujiabao.orderservice.service;

import ltd.dujiabao.orderservice.dao.OrderRepository;
import ltd.dujiabao.orderservice.dao.OutboxMessageRepository;
import ltd.dujiabao.orderservice.domain.dto.CreateOrderDto;
import ltd.dujiabao.orderservice.domain.dto.OrderMessage;
import ltd.dujiabao.orderservice.domain.entity.Order;
import ltd.dujiabao.orderservice.domain.entity.OutboxMessage;
import ltd.dujiabao.orderservice.domain.enums.MessageStatus;
import ltd.dujiabao.utils.JsonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.UUID;

/**
 * @author Bowie Du
 * @date 2025/7/9 21:59
 */

@Service
public class OrderService {

    @Autowired
    private OrderRepository orderRepository;

    @Autowired
    private OutboxMessageRepository outboxMessageRepository;

    @Transactional(rollbackFor = Exception.class)
    public void createOrder(CreateOrderDto dto) {
        // 创建订单
        LocalDateTime now = LocalDateTime.now();
        Order order = new Order()
                .setUserId(dto.getUserId())
                .setProductId(dto.getProductId())
                .setQuantity(dto.getQuantity())
                .setCreatedAt(now)
                .setUpdatedAt(now);
        orderRepository.save(order);

        // 保存消息到本地消息表
        String messageId = UUID.randomUUID().toString();
        OrderMessage orderMessage = new OrderMessage(dto.getProductId(), dto.getQuantity());
        OutboxMessage outboxMessage = new OutboxMessage()
                .setMessageId(messageId)
                .setExchange("inventory")
                .setRoutingKey("inventory")
                .setMessage(JsonUtils.toJson(orderMessage))
                .setStatus(MessageStatus.WAITING.getValue())
                .setRetryCount(0)
                .setCreatedAt(now)
                .setUpdatedAt(now);
        outboxMessageRepository.save(outboxMessage);
    }
}
